#include "InSdkTcpSystem.h"

#define DEF_TAG         "SdkTcp"

#define DEF_INNSDK_INTERNAL_MAX_NUM         10

Com_s32 InSdkTcpSystem_CreatSocket(Com_void)
{
    Com_s32 listen_socket = socket(AF_INET, SOCK_STREAM, 0);
    if(listen_socket == DEF_COM_FAILED)
    {
        perror("SdkTcp: socket");
        return DEF_COM_FAILED;
    }

    struct sockaddr_in addr;
    memset(&addr, 0, sizeof(addr));

    addr.sin_family = AF_INET;
    addr.sin_port = htons(DEF_INNSDK_TCP_SYSTEM_PORT);
    addr.sin_addr.s_addr = htonl(INADDR_ANY);

    Com_s32 ret = bind(listen_socket, (struct sockaddr *)&addr, sizeof(addr));
    if(ret == DEF_COM_FAILED)
    {
        perror("SdkTcp: bind");
        return DEF_COM_FAILED;
    }

    ret = listen(listen_socket,DEF_INNSDK_INTERNAL_MAX_NUM);
    if(ret == DEF_COM_FAILED)
    {
        perror("SdkTcp: listen");
        return DEF_COM_FAILED;
    }

    return listen_socket;
}

Com_s32 InSdkTcpSystem__WaitClient(Com_s32 listen_socket)
{
    struct sockaddr_in cliaddr;
    Com_s32 addrlen = sizeof(cliaddr);

    /** 创建一个和客户端交流的套接字 **/
    int client_socket = accept(listen_socket, (struct sockaddr *)&cliaddr,(socklen_t *)&addrlen);
    if(client_socket == DEF_COM_FAILED)
    {
        perror("accept");
        return DEF_COM_FAILED;
    }

    return client_socket;
}

Com_void InSdkTcpSystem__Send(Com_s32 socket)
{
    send(socket,DEF_INNSDK_TCP_SYSTEM_HANDLE_OK,strlen(DEF_INNSDK_TCP_SYSTEM_HANDLE_OK),MSG_NOSIGNAL);
}

Com_void InSdkTcpSystem__HandleClient(Com_s32 socket)
{
    StSdkTcpSystemInfo info;

    memset(&info,0,sizeof(info));

    while(DEF_COM_TRUE)
    {
        Com_s32 ret = recv(socket,&info,DEF_INNSDK_TCP_SYSTEM_SIZE - 1,MSG_DONTWAIT);
        if(ret > 0)
        {
            if(info.len != (ret - 4))
            {
                PRT_ERR(DEF_TAG,"recv %d,len: %d\n",ret,info.len);
                break;
            }

            PRT_INFO(DEF_TAG,"system--> %s\n",info.data);
            system(info.data);
            InSdkTcpSystem__Send(socket);
            break;
        }
        usleep(10 * 1000);
    }

    sleep(1);
    close(socket);
}

Com_s32 main(Com_void)
{
    Com_s32 listen_socket = InSdkTcpSystem_CreatSocket();

    while(DEF_COM_TRUE)
    {
        pthread_t id;
        Com_s32 client_socket;

        client_socket = InSdkTcpSystem__WaitClient(listen_socket);
        pthread_create(&id, NULL,(Com_pvoid)InSdkTcpSystem__HandleClient,(Com_pvoid)client_socket);
        pthread_detach(id);
        usleep(50 * 1000);
    }

    close(listen_socket);

    return DEF_COM_SUCCESS;
}
